package roosterparser;
import java.io.*;
import java.util.*;

import org.w3c.dom.html.HTMLElement;

import net.htmlparser.jericho.*;

public class RoosterParser {
	Rooster rooster;
	Calendar maandagDatum;
	ArrayList<String> kolomTitels;
	
	public RoosterParser(InputStream input, Rooster rooster, Calendar startDatum) throws Exception {
		Source source = new Source(input);
		this.rooster = rooster;
		this.maandagDatum = startDatum;
		
		parseRoosterTabel(source.getFirstElementByClass("spreadsheet"));
		System.out.println("Done parsing");
	}
	
	private void parseRoosterTabel(Element roosterTabel) {
		parseKolomTitels(roosterTabel.getFirstElementByClass("columnTitles"));
		HashMap<String, String> cursusData;
		
		for (Element tr : roosterTabel.getAllElements(HTMLElementName.TR)) {
			String className = tr.getAttributeValue("class");
			if (className == null || !className.equals("columnTitles")) {
				cursusData = parseCursus(tr.getAllElements(HTMLElementName.TD));
				
				if (cursusData.size() > 0) {
					createAndAddCursus(cursusData);
				}
			}
		}
	}
	
	private ArrayList<Integer> parseWeken(String input) {
		ArrayList<Integer> weekNummers = new ArrayList<Integer>();
		
		String[] weken = input.split(",\\s*");
		for (int i=0 ; i < weken.length ; i++) {
			if (weken[i].contains("-")) {
				String[] reeks = weken[i].split("\\s*-\\s*");
				int start = Integer.parseInt(reeks[0]), eind = Integer.parseInt(reeks[1]);
				for (int week = start ; week <= eind ; week ++) {
					weekNummers.add(week);
				}
			} else {
				weekNummers.add(Integer.parseInt(weken[i]));
			}
		}
		
		return weekNummers;
	}
	
	private void parseKolomTitels(Element titelsTR) {
		kolomTitels = new ArrayList<String>();
		List<Element> titels = titelsTR.getAllElements(HTMLElementName.TD);
		for (Element kolomTitel : titels) {
			String titel = kolomTitel.getContent().toString();
			titel = titel.split("\\W")[0];
			kolomTitels.add(titel.toLowerCase());
		}
	}
	
	private HashMap<String, String> parseCursus(List<Element> cursusBlok) {
		HashMap<String, String> cursusData = new HashMap<String, String>();
		
		for (int i = 0 ; i < cursusBlok.size() ; i++) {
			cursusData.put(kolomTitels.get(i), cursusBlok.get(i).getContent().toString());
		}
		
		return cursusData;
	}
	
	private void createAndAddCursus(HashMap<String, String> cursusData) {
		Cursus c = new Cursus(cursusData, (Calendar)maandagDatum.clone());
		rooster.addCursus(c);
	}
	
	public static void main(String[] args) throws Exception {
		FileInputStream fio = new FileInputStream("showtimetable.aspx.htm");
		Rooster r = new Rooster("ICT", "Technische Informatica", "V 2I");
		Calendar startDate = Calendar.getInstance();
		startDate.set(2011, 1, 14);
		
		// Force recompute of required fields. Otherwise things go pear shaped.
		startDate.getTime();

		new RoosterParser(fio, r, startDate);
		r.toGCalCSVImport();
	}
}
